package com.markerhub.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.User;
import com.markerhub.service.UserService;
import com.markerhub.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.util.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
@Slf4j
@RestController
public class AccountController {
    @Autowired
    UserService userService;
    @Autowired
    JwtUtils jwtUtils;
    /*
    进行登入
     */
    @CrossOrigin
    @PostMapping("/login")
    public Result Login(@Validated @RequestBody LoginDto loginDto,HttpServletResponse response){
        //根据用户名字进行查询

        User user = userService.getOne(new QueryWrapper<User>().eq("username",loginDto.getUsername()));
       log.info("登入获取信息============》"+user.toString());
        Assert.notNull(user,"用户名字不存在");
        if(!(user.getPassword()).equals(SecureUtil.md5(loginDto.getPassword()))){
            //判断密码是不是正确
            return Result.fail("密码错误");
        }
        //根据用户id生成jwt
       String jwt= jwtUtils.generateToken(user.getId());
        log.info("生成的jwt============》"+jwt);
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");
        return Result.succ(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("avatar", user.getAvatar())
                .put("email", user.getEmail())
                .map()
        );



    }

    // 退出
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }
}
